package com.juku2024.juku.fragment

import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import androidx.recyclerview.widget.RecyclerView
import com.juku2024.juku.DownloadDetailActivity
import com.juku2024.juku.DownloadEpisodeListActivity
import com.juku2024.juku.R
import com.juku2024.juku.adapter.DownloadAlbumAdapter
import com.juku2024.juku.base.BaseFragment
import com.juku2024.juku.dialog.CommonDialog
import com.juku2024.juku.model.AlbumListItemModel
import com.juku2024.juku.model.DownloadActionModel
import com.juku2024.juku.tools.AppUtils
import com.juku2024.juku.tools.Constants
import com.juku2024.juku.tools.LogC
import com.juku2024.juku.tools.WrapLinearLayoutManager
import com.juku2024.juku.viewmodel.DownloadViewModel
import com.juku2024.juku.widget.LoadingView
import com.wanban.download.db.DownloadEntity
import com.wanban.download.model.Status
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

class DownloadFinishedFragment : BaseFragment() {

    private var deleteDialog: CommonDialog? = null
    private val adapter by lazy { DownloadAlbumAdapter(ArrayList()) }
    private val viewModel by lazy { getViewModel(DownloadViewModel::class.java) }

    private lateinit var recyclerFinish: RecyclerView
    private lateinit var loadingView: LoadingView
    private lateinit var btnAll: Button
    private lateinit var btnDelete: Button
    private lateinit var editLayout: View

    override fun layoutView(inflater: LayoutInflater, container: ViewGroup?): View {
        return inflater.inflate(R.layout.fragment_download_finished, container, false)
    }

    override fun initView(rootView: View) {
        super.initView(rootView)
        recyclerFinish = rootView.findViewById(R.id.recyclerFinish)
        loadingView = rootView.findViewById(R.id.loadingView)
        btnAll = rootView.findViewById(R.id.btnAll)
        btnDelete = rootView.findViewById(R.id.btnDelete)
        editLayout = rootView.findViewById(R.id.editLayout)

        recyclerFinish.layoutManager = WrapLinearLayoutManager(requireContext())
        recyclerFinish.setHasFixedSize(true)
        recyclerFinish.adapter = adapter
    }

    override fun init(savedInstanceState: Bundle?) {
        super.init(savedInstanceState)
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this)
        }

    }

    override fun onResume() {
        super.onResume()
        loadingView.showLoading()
        viewModel.getAlbumList({
            if (isFragmentNotActive()) return@getAlbumList
            loadingView.hideLoading()
            if (it.isEmpty()) {
                loadingView.showEmptyStatus(getString(R.string.dl_no_downloaded))
                return@getAlbumList
            }
            adapter.setList(it)
        }, {
            if (isFragmentNotActive()) return@getAlbumList
            loadingView.hideLoading()
            loadingView.showEmptyStatus(getString(R.string.dl_no_downloaded))
        })
    }


    override fun bindEvent() {
        super.bindEvent()
        adapter.setOnItemClickListener { _, _, position ->
            val item = adapter.data[position]
            if (adapter.isShowCheck) {
                item.isSelected = !item.isSelected
                adapter.notifyItemChanged(position)
                modifySelectNum()
            } else {
                val intent = Intent(requireContext(), DownloadEpisodeListActivity::class.java)
                intent.putExtra(Constants.AROUTER_KEY_VIDEO_ID, item.videoId)
                intent.putExtra(Constants.AROUTER_KEY_VIDEO_NAME, item.name)
                startActivity(intent)
            }
        }

        btnAll.setOnClickListener {
            val count = adapter.data.count { it.isSelected }
            if (count == adapter.data.size) {
                adapter.data.forEach { it.isSelected = false }
            } else {
                adapter.data.forEach { it.isSelected = true }
            }
            adapter.notifyDataSetChanged()
            modifySelectNum()
        }

//        btnDelete.setOnClickListener {
//            if (isFragmentNotActive() || adapter.data.isNullOrEmpty()) return@setOnClickListener
//            if (deleteDialog == null) {
//                deleteDialog = CommonDialog(requireActivity())
//            }
//            deleteDialog?.showDialog(
//                "您确认删除选中的缓存内容吗？",
//                getString(R.string.confirm), {
//                    val deletes = ArrayList<AlbumListItemModel>()
//                    deletes.addAll(adapter.data.filter { it.isSelected })
//                    deletes.forEach {
//                        // 删除数据
//                        adapter.remove(it)
//                        if (SPUtil.instance.downloadType) {
//                            viewModel.deleteDbAndData(it)
//                        } else {
//                            MultiDownloadManager.deleteDownload(it.downloadUrl)
//                        }
//                    }
//                    modifySelectNum()
//                    if (adapter.data.isEmpty()) {
//                        editLayout.visibility = View.GONE
//                        adapter.isShowCheck = false
//                        loadingView.showEmptyStatus(getString(R.string.dl_no_downloaded))
//                        (requireActivity() as DownloadDetailActivity).resetEditStatus()
//                    }
//                    deleteDialog?.dismiss()
//                }, getString(R.string.cancel), {
//                    deleteDialog?.dismiss()
//                }
//            )
//            deleteDialog?.show()
//        }
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onDownloadEvent(event: DownloadEntity) {
        if (isFragmentNotActive()) return
        onRxDownloadEventM3U8(event)
    }

    private fun onRxDownloadEventM3U8(downloadEntity: DownloadEntity) {
        if (downloadEntity.state == Status.SUCCESS) { // 删除
            val index = adapter.data.indexOfFirst { it.videoId == downloadEntity.videoId }
            if (index != -1) {
                val target = adapter.data[index]
                target.albumTotalLength -= downloadEntity.contentLength
                target.albumCount -= 1
                if (target.albumCount > 0) {
                    adapter.notifyItemChanged(index)
                } else {
                    adapter.removeAt(index)
                }
            }
            if (adapter.data.isEmpty()) {
                adapter.setList(ArrayList())
                loadingView.showEmptyStatus(getString(R.string.dl_no_downloaded))
            }
            return
        }

        if (downloadEntity.state != Status.SUCCESS) return

        // 判断是已经有此视频
        var hasAddedVideo = false
        for (album in adapter.data) {
            // 如果有此视频
            hasAddedVideo = album.albums?.any { it.url == downloadEntity.url }?:false
            if (hasAddedVideo) {
                break
            }
        }
        if (hasAddedVideo) {
            return
        }

        val index = adapter.data.indexOfFirst { it.videoId == downloadEntity.videoId }
        if (index == -1) {
            val item = AlbumListItemModel()
            item.videoId = downloadEntity.videoId
            item.name = downloadEntity.videoName
            item.pic = downloadEntity.coverUrl
            item.albumCount = 1
            item.albumTotalLength = downloadEntity.contentLength
            item.albums = ArrayList()
            item.albums?.add(downloadEntity)

            adapter.addData(item)
        } else {
            val target = adapter.data[index]
            target.albumTotalLength += downloadEntity.contentLength
            target.albumCount += 1
            target.albums?.add(downloadEntity)
            adapter.notifyItemChanged(index)
        }
        loadingView.hideLoading()
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onDownloadAction(actionModel: DownloadActionModel) {
        if (actionModel.currentItem != 1) return
        if (adapter.data.isEmpty()) return
        // 更改编辑按钮的状态
        (requireActivity() as DownloadDetailActivity).changeEditStatus()
        changeEditUI(actionModel.isShowEditStatus)
    }

    private fun changeEditUI(isShowEditUI: Boolean){
        adapter.isShowCheck = isShowEditUI
        adapter.data.forEach { it.isSelected = false }
        adapter.notifyDataSetChanged()
        btnDelete.setTextColor(AppUtils.getColor(R.color.color_text_dark))
        btnDelete.text = String.format(AppUtils.getString(R.string.delete))
        btnAll.text = getString(R.string.select_all)
        editLayout.visibility = if (isShowEditUI) { View.VISIBLE } else { View.GONE }
    }


    private fun modifySelectNum() {
        if (adapter.data.isEmpty()) {
            return
        }
        val count = adapter.data.count { it.isSelected }
        if (count != 0) {
            val text = if (count >= adapter.data.size) {
                getString(R.string.cancel_select_all)
            } else {
                getString(R.string.select_all)
            }
            btnAll.text = text
            btnDelete.setTextColor(AppUtils.getColor(R.color.color_text_light))
            btnDelete.text = String.format(AppUtils.getString(R.string.delete_num), count)
        } else {
            btnDelete.setTextColor(AppUtils.getColor(R.color.color_text_dark))
            btnDelete.text = String.format(AppUtils.getString(R.string.delete))
            btnAll.text = getString(R.string.select_all)
        }
    }

    private fun updateEditUI() {
        if (adapter.isShowCheck) {
            editLayout.visibility = View.VISIBLE
        } else {
            editLayout.visibility = View.GONE
        }
        adapter.notifyDataSetChanged()
    }

    override fun onDestroy() {
        super.onDestroy()
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this)
        }
    }

    override fun onStop() {
        super.onStop()
        deleteDialog?.dismiss()
    }
}